<template>
	<div class="tanModelbox application-dialog">
		<div class="application-dialog-main-content">
			<div class="real-header">会员申请<i class="application-close" @click="closeDialog"></i></div>
			<div class="application-dialog-inner-content" ref="scrollWrap">
				<div class="loading" v-if="initLoading"><img src="@/assets/images/loading.gif" alt="" class="loading-img"/><span>玩命加载中...</span></div>
				<div style="min-height:calc(100vh - 1.8rem); padding-bottom: 5rem;" v-else>
					<div class="application-reject-wrap" v-if="applicationStatus === 2">
						<h3 style="color:#000">您的申请被驳回，请按照要求重新填写：</h3>
						<div class="application-reject-reason" style="word-break:break-all">{{applicationRejectReason}}</div>
					</div>
					<div class="application-header" v-if="applicationStatus !== 2">
						<div class="application-header-tips" style="word-break:break-all">{{headerTips}}</div>
					</div>
					<div class="form-area-wrap">
						<div class="form-area">
							<ul class="form-list">
								<li class="form-list-wrap no-border">
									<label for="name" class="form-list-label">姓名</label><input type="text" placeholder="请填写姓名" id="name" class="form-list-input"
									 v-model="applicationQuery.name" v-input/>
								</li>
								<li class="form-list-wrap">
									<label class="form-list-label"></label>
									<div class="male-wrap">
										<div>
											<input type="radio" id="male" name="sex" value="男" v-model="sex_show" checked /><label for="male">先生</label>
										</div>
										<div class="female">
											<input type="radio" id="female" name="sex" value="女" v-model="sex_show" /><label for="female">女士</label>
										</div>
									</div>
								</li>
								<li class="form-list-wrap">
									<label for="telephone" class="form-list-label">手机</label><input type="text" novalidate="novalidate" pattern="[0-9]*"
									 placeholder="请填写手机号" id="telephone" class="form-list-input" maxlength="11" v-model="applicationQuery.cellphone" v-input/>
								</li>
							</ul>
						</div>
						<div class="form-area">
							<ul class="form-list">
								<li class="form-list-wrap">
									<label for="location" class="form-list-label">地区</label><input ref="location" id="location" class="form-list-input"
									 placeholder="请填写城市" v-model="city_area" readonly v-input>
								</li>
								<li class="form-list-wrap">
									<label for="address" class="form-list-label">地址</label><input type="text" placeholder="请填写地址" id="address"
									 class="form-list-input" v-model="applicationQuery.address" v-input/>
								</li>
							</ul>
						</div>
						<div class="form-area">
							<ul class="form-list">
								<li class="form-list-wrap">
									<label for="remark" class="form-list-label">备注</label><textarea name="remark" rows="" cols="" id="remark"
									 class="form-list-input" style="height: 4.25rem;line-height: 1.5rem;padding: 0.62rem 0;" v-model="applicationQuery.remark" v-input> </textarea>
								</li>
							</ul>
						</div>
						<div class="submit-btn-wrap">
							<a href="javascript:;" class="submit-btn" :class="{'disabled':applicationSecondTimer}" @click.self="submitApplication">{{btnTips}}<span
								 v-show="applicationSecondTimer">({{applicationSecond}}S)</span></a>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import input from '@/directive/input/input';
import SmartScroll from '@/utils/SmartScroll';
import {
  getCityAreaList,
  getApplication,
  updateApplication,
  insertApplication
} from '@/api/application';

export default {
  name: 'application',
  directives: {
	  input
  },
  data() {
    return {
      cityArr: [],
      // picker选中的值
      city_area_id_arr: [],
      city_area: '请填写城市',
      sex_show: '男',
      applicationQuery: {
        name: '',
        city_area_id: undefined,
        sex: 0,
        cellphone: '',
        remark: '',
        address: '',
        room_id: parseInt(this.roomId)
      },
      applicationSecond: 60,
      applicationSecondTimer: null,
      applicationStatus: undefined,
      headerTips: '完善个人信息更容易通过审核',
      btnTips: '提交',
      applicationRejectReason: '',
			initLoading:false
    };
  },
  props: {
    roomId: {
      type: String
    }
  },
  methods: {
		reset(){
			this.city_area_id_arr =  []
			this.city_area = '请填写城市'
			this.sex_show =  '男'
			this.applicationQuery = {
			  name: '',
			  city_area_id: undefined,
			  sex: 0,
			  cellphone: '',
			  remark: '',
			  address: '',
			  room_id: parseInt(this.roomId)
			}
			this.applicationSecond = 60
			this.applicationSecondTimer =  null
			this.applicationStatus = undefined
			this.headerTips = '完善个人信息更容易通过审核'
			this.btnTips =  '提交'
			this.applicationRejectReason = ''
		},
    closeDialog() {
      this.$emit('close');
    },
    filterCity(cityArr) {
      const arr = [];
      cityArr.forEach(item => {
        const obj = {};
        obj.name = item.name;
        obj.area_id = item.id;
        if (item.children && item.children.length > 0) {
          obj.sub = this.filterCity(item.children);
        }
        arr.push(obj);
      });
      return arr;
    },
    initArea(city, selected) {
      const nameEl = this.$refs.location
      const first = []; /* 省，直辖市 */
      let second = []; /* 市 */
      const selectedIndex = selected || [0, 0]; /* 默认选中的地区 */
      const checked = [0, 0]; /* 已选选项 */

      function creatList(obj, list) {
        obj.forEach((item, index, arr) => {
          const temp = new Object();
          temp.text = item.name;
          temp.value = item.area_id;
          list.push(temp);
        });
      }
      creatList(city, first);
      if (city[selectedIndex[0]].hasOwnProperty('sub')) {
        creatList(city[selectedIndex[0]].sub, second);
      } else {
        second = [{
          text: '',
          value: 0
        }];
      }
      if (document.querySelector('.picker')) {
        document.querySelector('.picker').parentNode.removeChild(document.querySelector('.picker'));
      }
      const picker = new Picker({
        data: [first, second],
        selectedIndex,
        title: '请选择城市'
      });
      picker.on('picker.select', (selectedVal, selectedIndex) => {
        const text1 = first[selectedIndex[0]].text;
        const text2 = second[selectedIndex[1]].text;
        this.city_area = `${text1} ${text2}`;
      });

      picker.on('picker.change', (index, selectedIndex) => {
        if (index === 0) {
          firstChange();
        }

        function firstChange() {
          second = [];
          checked[0] = selectedIndex;
          const firstCity = city[selectedIndex];
          if (firstCity.hasOwnProperty('sub')) {
            creatList(firstCity.sub, second);
            const secondCity = city[selectedIndex].sub[0];
          } else {
            second = [{
              text: '',
              value: 0
            }];
            checked[1] = 0;
          }

          picker.refillColumn(1, second);
          picker.scrollColumn(1, 0);
        }
      });

      picker.on('picker.valuechange', (selectedVal, selectedIndex) => {
        this.city_area_id_arr = selectedVal;
        this.applicationQuery.city_area_id = this.city_area_id_arr[1];
      });
			nameEl.addEventListener('click', () => {
				picker.show();
			});
    },
    submitApplication() {
      if (this.applicationSecondTimer) {
        this.$layer.open({
          content: '60S内不能重复提交!',
          skin: 'msg',
          time: 2 // 2秒后自动关闭
        });
        return false;
      }
      if (this.applicationQuery.cellphone) {
        if (!/^1\d{10}$/.test(this.applicationQuery.cellphone)) {
          this.$layer.open({
            content: '您填写的手机号码不正确!',
            skin: 'msg',
            time: 2 // 2秒后自动关闭
          });
          return false;
        }
      }
      if (this.applicationQuery.remark) {
        if (this.applicationQuery.remark.length > 20) {
          this.$layer.open({
            content: '备注不能超过20字!',
            skin: 'msg',
            time: 2 // 2秒后自动关闭
          });
          return false;
        }
      }
      if (this.applicationStatus === 1 || this.applicationStatus == 2) {
        updateApplication(this.applicationQuery).then(res => {
          this.$layer.open({
            content: '您的信息已提交审核，请耐心等待!',
            skin: 'msg',
            time: 2 // 2秒后自动关闭
          });
          this.getApplicationFunc(this.cityArr);
          this.applicationSecondTimer = setInterval(() => {
            this.applicationSecond--;
            if (this.applicationSecond == 0) {
              clearInterval(this.applicationSecondTimer);
              this.applicationSecondTimer = null;
              this.applicationSecond = 60;
            }
          }, 1000);
        });
      } else {
        insertApplication(this.applicationQuery).then(res => {
          this.$layer.open({
            content: '您的信息已提交审核，请耐心等待!',
            skin: 'msg',
            time: 2 // 2秒后自动关闭
          });
          this.getApplicationFunc(this.cityArr);
          this.applicationSecondTimer = setInterval(() => {
            this.applicationSecond--;
            if (this.applicationSecond == 0) {
              clearInterval(this.applicationSecondTimer);
              this.applicationSecondTimer = null;
              this.applicationSecond = 60;
            }
          }, 1000);
        });
      }
    },
    getParent(city, id) {
      let arr = [];
      for (let i = 0; i < city.length; i++) {
        for (let j = 0; j < city[i].sub.length; j++) {
          if (city[i].sub[j].area_id == id) {
            arr = [i, j];
            break;
          }
        }
      }
      return arr;
    },
    getApplicationFunc(city) {
      getApplication({
        room_id: parseInt(this.roomId)
      }).then(res => {
        let selected;
        if (res.data) {
          if (res.data.status) {
            this.applicationStatus = res.data.status;
            if (res.data.status === 1) {
              this.headerTips = '您的信息已提交审核，请耐心等待!';
              this.btnTips = '修改';
              this.applicationRejectReason = '';
            } else if (res.data.status === 2) {
              this.applicationRejectReason = res.data.reason;
            } else if (res.data.status === 3) {
              location.reload();
            }
            if (res.data.city_area_id && res.data.city_area_id !== '0') {
              selected = this.getParent(city, res.data.city_area_id);
            }
            this.applicationQuery.name = res.data.name;
            if (res.data.sex == 0) {
              this.sex_show = '男';
            } else {
              this.sex_show = '女';
            }
            this.applicationQuery.cellphone = res.data.cellphone;
            this.applicationQuery.remark = res.data.remark;
            this.applicationQuery.address = res.data.address;
            if (selected) {
              this.city_area = `${city[selected[0]].name} ${city[selected[0]].sub[selected[1]].name}`;
              this.applicationQuery.city_area_id = selected[1];
            }
          }
        }else{
					this.reset()
				}
				this.initLoading = false
				this.$nextTick(()=>{
					this.initArea(city, selected)
				})
      }).catch(err => {
				this.initLoading = false
        console.log(err.message);
      });
    },
    init() {
			this.initLoading = true
      if (this.cityArr.length > 0) {
        this.getApplicationFunc(this.cityArr);
      } else {
        getCityAreaList().then(res => {
          const cityObj = res.data;
          Object.keys(cityObj).forEach(key => {
            this.cityArr.push(cityObj[key]);
          });
          this.cityArr = this.filterCity(this.cityArr);
          return this.cityArr;
        }).then(cityArr => {
          this.$nextTick(() => {
							import('./util/picker.min.js').then(() => {
							  this.getApplicationFunc(cityArr);
							});
          });
        });
      }
    }
  },
  watch: {
    sex_show(newVal, oldVal) {
      this.applicationQuery.sex = newVal === '男' ? 0 : 1;
    }
  },
	mounted(){
		new SmartScroll(document.querySelector('.application-dialog'), document.querySelector('.application-dialog-inner-content'));
	}
};
</script>
<style scoped>
	.loading{
		padding: 0.62rem;
		text-align: center;
	}
	.loading .loading-img{
		width: 1.87rem;
		height: 1.87rem;
		vertical-align: middle;
	}
	.application-dialog {
		position: fixed;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		overflow: hidden;
		z-index: 1001;
		background-color: #f6f6f6;
		transition: transform .15s;
		transform: translateY(0);
		animation-fill-mode:both;
		animation-duration:0.2s;
	}

	.application-dialog.active {
		transform: translateY(0);
	}

	.application-dialog .application-dialog-main-content {
		background-color: #f6f6f6;
	}

	.application-dialog-inner-content {
		height: calc(100vh - 2.75rem);
		overflow: scroll;
		-webkit-overflow-scrolling: touch;
	}

	.real-header {
		position: relative;
		height: 2.75rem;
		font-size: 1.12rem;
		line-height: 2.75rem;
		color: #232323;
		text-align: center;
		font-weight: 600;
		background-color: #fff;
	}

	.application-header {
		padding: 1rem 0.75rem;
		background-color: #f6f6f6;
		color: #000;
		font-size: 1rem;
		line-height: 1.5rem
	}

	.form-area {
		width: 100%;
		background-color: #fff;
		margin-bottom: 0.75rem;
	}

	.form-list-wrap {
		position: relative;
		display: flex;
		padding: 0.31rem 0;
		font-size: 1rem;
		border-bottom: 1px solid #e6e6e6;
	}

	.form-list-wrap:last-child,
	.no-border {
		border-bottom: 0 none;
	}

	.no-border.form-list-wrap::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 5.37rem;
		right: 0;
		border-bottom: 1px solid #e6e6e6;
	}

	.form-list-label {
		width: 5.37rem;
		margin-top: 0.5rem;
		text-align: center;
	}

	.form-list-input {
		flex: 1;
		vertical-align: middle;
		height: 2.5rem;
		line-height: 2.5rem;
		background: none;
		border: none;
		outline: none;
		font-size: 1rem
	}

	.form-list-wrap input[type='radio'] {
		position: absolute;
		clip: rect(0, 0, 0, 0)
	}

	.form-list-wrap input[type='radio']+label::before {
		content: "\a0";
		display: inline-block;
		vertical-align: middle;
		width: 1rem;
		height: 1rem;
		margin-right: 0.87rem;
		border: 1px solid #979797;
		border-radius: 50%;
	}

	.form-list-wrap input[type='radio']:checked+label::before {
		background: url(./images/proper.png) no-repeat;
		background-size: contain;
		border: 0 none;
		padding: 1px;
	}

	.form-list-wrap .male-wrap {
		display: flex;
		align-items: center;
		height: 3.12rem;
	}

	.form-list-wrap .female {
		margin-left: 2.18rem;
	}

	:-moz-placeholder {
		/* Mozilla Firefox 4 to 18 */
		color: #000;
		opacity: 1;
	}

	::-moz-placeholder {
		/* Mozilla Firefox 19+ */
		color: #000;
		opacity: 1;
	}

	input:-ms-input-placeholder {
		color: #000;
		opacity: 1;
	}

	input::-webkit-input-placeholder {
		color: #000;
		opacity: 1;
	}

	.submit-btn-wrap {
		margin-top: 2.18rem;
		text-align: center;
	}

	.submit-btn {
		display: inline-block;
		width: 19.68rem;
		line-height: 3.12rem;
		text-align: center;
		background-color: #4360F0;
		color: white !important;
		border-radius: 1.87rem;
		font-size: 1rem;
	}

	.submit-btn.disabled {
		background-color: #ccc;
	}

	.submit-btn span {
		display: inline-block;
		margin-left: 10px;
	}

	.application-close {
		position: absolute;
		top: 0;
		bottom: 0;
		right: 20px;
		margin: auto;
		width: 1rem;
		height: 1rem;
		background: url(./images/application_close.png) no-repeat;
		background-size: contain;
	}

	.application-reject-wrap {
		margin: 0.75rem 0;
		padding: 1rem 0.75rem;
		color: #666;
		font-size: 1rem;
		background-color: #fff;
	}
</style>
<style>
	.picker {
		z-index: 1002 !important;
	}

	.picker .picker-panel .picker-choose .picker-title {
		font-size: 0.87rem !important;
	}

	.picker .picker-panel .picker-choose .confirm {
		color: #1c72fa !important;
	}
</style>
